/*  
 * cafe-timeline.js
 * 预报预警时间轴
 */
; define(function () {
	'use strict';
	function getNodeHtml(cfg) {
		if (!cfg.startTime) return;
		$(cfg.appendTo).find(".cafe-busis-timeline").remove();

		var $container = $('<div>').addClass('cafe-busis-timeline');
		var $leftContainer = $('<div>').addClass('timeline-body');

		var startTime = new Date(cfg.startTime);

		var $ul = $('<ul>');
		var $sk_li = $(`<li class="sk"><span></span><span>${startTime.format("hh:mm")}</span></li>`);

		$sk_li.data('time', startTime.format("yyyy-MM-dd hh:mm:ss"));
		$sk_li.attr('title', startTime.format("yyyy-MM-dd hh:mm:ss"));

		$ul.append($sk_li);

		// 初始化短临时间轴
		var lastDlTime, timeStr;
		var dlInterval = cfg.dlInterval * 60 * 1000;
		var dlCounts = cfg.dlLen * 60 / cfg.dlInterval;
		for(var i = 1; i <= dlCounts; i++){
			var tempTime = new Date(startTime.getTime() + dlInterval * i);
			lastDlTime = tempTime;
			var $dl_li = $(`<li><span></span><span>${tempTime.format("hh:mm")}</span></li>`);
			$dl_li.data('time', tempTime.format("yyyy-MM-dd hh:mm:ss"));
			$dl_li.attr('title', tempTime.format("yyyy-MM-dd hh:mm:ss"));
			$dl_li.addClass('yb');
			$ul.append($dl_li);
		}

		// 初始化短期时间轴
		var dqInterval = cfg.dqInterval * 60 * 60 * 1000;
		var startDate = new Date(lastDlTime.getTime() + dqInterval);
		var clsNm = '';
		for (var i = 0; i < cfg.dqLen; i++) {
			var tempTime = new Date(startDate.getTime() + dqInterval * i);
			tempTime.setMinutes(0);
			if (tempTime.getHours() == 0) {
				timeStr = tempTime.format("dd日");
				clsNm = 'day'
			} else {
				timeStr = tempTime.format("hh:mm");
				clsNm = '';
			}
			var $dq_li = $(`<li><span></span><span class=${clsNm}>${timeStr}</span></li>`);
			$dq_li.data('time', tempTime.format("yyyy-MM-dd hh:mm:ss"));
			$dq_li.attr('title', tempTime.format("yyyy-MM-dd hh:mm:ss"));
			$dq_li.addClass('yb');
			$ul.append($dq_li);
		}

		$ul.css('width', $ul.find('li').length * 47);
		$leftContainer.append($ul);

		$container.append($leftContainer);

		$container.append('<div class="timeline-control">' +
			'<span class="timeline-prev" flag="prev"></span>' +
			'<span class="timeline-play" flag="play"></span>' +
			'<span class="timeline-next" flag="next"></span>' +
			'<span class="timeline-slow timeline-speed active" flag="slow" speed="4"></span>' +
			'<span class="timeline-fast timeline-speed" flag="fast" speed="2"></span>' +
			'<span class="timeline-fly timeline-speed" flag="fly" speed="1"></span>' +
			'<span class="timeline-reset" flag="reset"></span>' +
			'</div>')
		return $container;
	}

	function buildWarning($drop, cfg) {
		$drop.find(".timeline-body>ul>li").find('ul').remove();
		$drop.find(".timeline-body>ul>li").each(function (index, item) {
			var time = $(this).data("time");
			var warnlist = cfg.data[time];
			if (!warnlist) return;
			var len = Math.round($drop.find(".timeline-body").width() / 47);
			var $ul = $('<ul>'), warnTypeArr = {};
			for (var key in warnlist) {
				var warnData = warnlist[key];
				if (warnData.length == 0) {
					delete warnlist[key];
					continue;
				}
				var warnType = cfg.warnCfg.warnType[key.replace('S_', '').replace('Z_', '')];
				if (warnTypeArr.hasOwnProperty(warnType)) {
					warnTypeArr[warnType][key] = warnData;
					continue;
				} else {
					warnTypeArr[warnType] = {};
					warnTypeArr[warnType][key] = warnData;
				}
			}
			for (var key in warnTypeArr) {
				var $li = $(`<li class=${key}></li>`);
				$li.data('warnType', key);
				$li.data('warnData', warnTypeArr[key]);
				$ul.append($li);
			}
			if (index >= len) { // 默认超过可视区域隐藏
				$ul.hide();
			}
			$(this).append($ul);
			$(this).data('warnlist', warnlist);
			$(this).addClass("warn");
		})
	}
	// 实况时间轴点击事件
	function skTimeClick(that, cfg) {
		var time = $(that).data("time");
		var warnlist = $(that).data('warnlist');
		var warnTime = new Date(time).getTime();
		if ($.isFunction(cfg.skCall)) {
			cfg.skCall(warnTime, warnlist);
		}
	}
	// 预报时间轴点击事件
	function ybTimeClick(that, cfg) {
		var warnlist = $(that).data('warnlist');
		if ($.isFunction(cfg.ybCall)) {
			cfg.ybCall(warnlist);
		}
	}
	
	// 预报报警图标点击事件
	function ybWarnIconClick(that, cfg) {
		var warnData = $(that).data('warnData');
		var warnDesc = [], eleName;
		for (var key in warnData) {
			eleName = cfg.warnCfg.eleName[key.replace('Z_', '')];
			if (!eleName) return;
			warnData[key].forEach(data => {
				warnDesc.push((cfg.warnCfg.modeType[data.modelType] || '') + eleName + cfg.warnCfg.level[Number(data.warnLevel)-1] + '报警');
			});
		}
		if (warnDesc.length === 0) return;
		warnDesc = Array.from(new Set(warnDesc));
		$(that).attr('title', warnDesc.join('\n'))
	}
	function control(flag, appendTo) {
		var $body = appendTo.find(".timeline-body");
		var $drop = appendTo.find(".timeline-control");
		var totalLen = $body.find('>ul>li').length; // 时间总个数
		var len = Math.round($body.width() / 47);
		var left = Number($body.find('>ul').css("left").replace("px", ''));
		switch(flag) {
			case 'play':
				var $play  = $drop.find(".timeline-play");
				clearInterval($play.val());
				if(!$play.hasClass("active")){
					$play.addClass("active");
					var interval = -1
					var speed = $drop.find(".timeline-speed.active").attr("speed");
					if(!speed){
						speed = 3;
					}
					interval = setInterval(function(){
						control("next",appendTo);
					},speed * 500);
					$play.val(interval);
				}else{
					clearInterval($play.val());
					$play.removeClass("active");
				}
				
				break;
			case 'prev': 
				var $prevLi = $body.find(">ul>li.active").prev();
				if ($prevLi.length > 0) {
					var index = $body.find(">ul>li.active").index(); // 当前选中时间的下标
					if (index == 0) return;
					if (left != 0 && Math.abs(left) - len * 47 == (index - len) * 47) {
						$body.find('>ul').css("left", left + 47);

						$body.find('>ul>li').eq(index - 1).find('ul').show();
						$body.find('>ul>li').eq(index + len - 1).find('ul').hide();
					}
					$prevLi.click();
				}
				break;
			case 'next': 
				var $nextLi = $body.find(">ul>li.active").next();
				if ($nextLi.length > 0) {
					var index = $body.find(">ul>li.active").index() + 1; // 当前选中时间的下标
					if (index == totalLen) return;
					if (index >= len && Math.abs(left) == (index - len) * 47) {
						$body.find('>ul').css("left", left - 47);

						$body.find('>ul>li').eq(index).find('ul').show();
						$body.find('>ul>li').eq(index - len).find('ul').hide();
					}
					$nextLi.click();
				}
				break;
			case 'reset': 
				$body.find('>ul').css("left", 0);
				$body.find('>ul>li').each(function (i, item) {
					if (i < len)
						$(item).find('ul').show();
					else
						$(item).find('ul').hide();
				})
				var $firstLi = $body.find(">ul>li").first();
				$firstLi.click();
				break;
			case 'slow':
			case 'fast':
			case 'fly':
				appendTo.find('.timeline-speed[flag='+flag+']').addClass('active').siblings(".timeline-speed").removeClass('active');
				if(appendTo.find(".timeline-play").hasClass("active")){
					var $play  = $drop.find(".timeline-play");
					clearInterval($play.val());
					if($play.hasClass("active")){
						var interval = -1
						var speed = $drop.find(".timeline-speed.active").attr("speed");
						if(!speed){
							speed = 3;
						}
						interval = setInterval(function(){
							control("next",appendTo);
						},speed * 500);
						$play.val(interval);
					}
				}
				break;
		}
	}
	function bindEvent($drop, cfg) {
		$drop.find('.timeline-body').off('click').on("click", 'ul>li.sk', function () {
			$(this).addClass('active').siblings().removeClass('active');
			skTimeClick(this, cfg);
		}).on("click", 'ul>li.yb', function (event) {
			event.stopPropagation();
			$(this).addClass('active').siblings().find('li.active').removeClass('active');
			$(this).addClass('active').siblings().removeClass('active');
			$(this).find('li').addClass('active');
			ybTimeClick(this, cfg);
		}).on("mouseover", 'ul>li.yb.warn ul li', function (event) { // 预报报警图标点击事件
			event.stopPropagation();
			ybWarnIconClick(this, cfg);
		})
		$drop.find(".timeline-control span").click(function () {
			var flag = $(this).attr('flag');
			control(flag, $drop);
		})
	}

	var CFTimeline = function (settings) {
		var options = {
			appendTo: '',  // 时间轴所在容器
			mapId: '',
			data: [],       // 预报数据
			startTime: '',  // 开始时间
			dlLen: 2,     // 短临的预报时间, 默认2小时
			dlInterval: 10, // 短临的预报间隔, 默认10分钟
			dqLen: 70,      // 短期的预报时间, 默认70小时
			dqInterval: 1,  // 短期的预报间隔, 默认1小时
			close: null,    // 关闭时间轴事件
			skCall: null, // 报警图标点击事件
			ybCall: null, // 格点数据点击事件
			ybIconCall: null,
			warnIcon: null
		};
		this.config = $.extend({}, options, settings);
		this.$drop = getNodeHtml(this.config);
		if (this.config.appendTo) {
			$(this.config.appendTo).append(this.$drop);
		}
		bindEvent(this.$drop, this.config);
		buildWarning(this.$drop, this.config);
		$('.cafe-busis-timeline .timeline-body>ul>li.sk').trigger('click'); // 实况
	}

	CFTimeline.prototype = {
		close: function () {
			this.$drop.hide();
		},
		hideWarnIcon: function (type, isSK) {
			if (isSK) 
				this.$drop.find('li.sk').find('li.' + type).hide();
			else
				this.$drop.find('li.yb').find('li.' + type).hide();
		},
		showWarnIcon: function (type, isSK) {
			if (isSK) 
				this.$drop.find('li.sk').find('li.' + type).show();
			else
				this.$drop.find('li.yb').find('li.' + type).show();
		},
		clickActive: function() {
			this.$drop.find('li.yb.active').click();
		},
		getData: function() {
			return this.config.data;
		},
		updateData: function(data) {
			this.config.data = data;
			buildWarning(this.$drop, this.config);
		}
	};

	CafeJS.Timeline = function (settings) {
		var drop = new CFTimeline(settings);
		return drop;
	}
});